/**
 * https://uniapp.dcloud.io/api/request/request?id=request
 */
import $u from "@/u"

const request = ({
    url = "",
    data = {},
    header = {},
    withCredentials = false,
    method = "get",
    loading = true,
    retransmission = true,
}) => {
    if (loading) { $u.showLoading({ title: '加载中..' }) }
    return new Promise((resolve) => {
        _request({ url, data, header, withCredentials, method, loading, retransmission, resolve });
    });
}

const _request = ({ url, data, header = {}, withCredentials, method, loading, retransmission, resolve }) => {

    let option = {
        url, data, method, header, withCredentials,
        success({ data }) {
            resolve(data);
        },
        fail(e) {
            console.log(e)
            // 如果不需要重新传输
            if (!retransmission) {
                resolve({ data: null, success: false, msg: "网络连接异常" })
                return false;
            }
            // 失败重连
            setTimeout(() => {
                _request({ url, data, header, withCredentials, method, loading, retransmission, resolve })
            }, 3000);
        },
        async complete({ data }) {
            if (loading) $u.hideLoading();
            if (!data?.success && data?.msg) $u.toast({ title: data.msg })
        }
    }
    $u.request(option)
}

export default request